package com.trendata.mina.handler;

import java.util.Iterator;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;

import com.trendata.util.SingleMessageMap;
import com.trendata.util.SingleSessionMap;

/**
 * 处理服务器端消息
 * 
 */
public class ServerMessageHandler extends IoHandlerAdapter {
	private static final Logger logger = Logger.getLogger("serverSocketLogger");
	private static Map<String, IoSession> sessionMap;// 存储店铺session map
	private static Map<String, Object> messageMap;// 存储用户消息map
	static {
		sessionMap = SingleSessionMap.getInstance();
		messageMap = SingleMessageMap.getInstance();
	}

	@Override
	public void sessionCreated(IoSession session) throws Exception {
		logger.info("创建一个新连接:" + session.getRemoteAddress());
		System.out.println("有新连接进入");
	}

	@Override
	public void messageReceived(IoSession session, Object message) throws Exception {
		String content = message.toString();
		logger.info("服务器接收到数据长度：" + content.length());
		if (content.startsWith("shopOpenId")) {
			logger.info("客户端首次连接，获取shopOpenId");
			String key = content.substring(content.indexOf("=") + 1);
			sessionMap.put(key, session);
		} else {
			// 处理图片数据
			String userOpenId = content.substring(0, content.indexOf(":"));
			String base64Img = content.substring(content.indexOf(":") + 1);
			messageMap.put(userOpenId, base64Img);
		}
	}

	@Override
	public void sessionClosed(IoSession session) throws Exception {
		logger.info("关闭当前session:" + session.getId() + ":" + session.getBothIdleCount());
		Iterator<String> itr = sessionMap.keySet().iterator();
		while (itr.hasNext()) {
			String shopOpenId = itr.next();
			IoSession ioSession = sessionMap.get(shopOpenId);
			if (session.equals(ioSession)) {
				sessionMap.remove(shopOpenId);
				break;
			}
		}
		System.out.println("关闭socket");
		session.close(true);
	}

	@Override
	public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
		logger.error("服务器发生异常:" + cause.getMessage());
	}

}